package com.amado.course32;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;


/**
 * hashCode 如果两个对象调用equals相等，那它们的hashCode方法值必须一样
 * <p>
 * hashCode值一样，他们的equals并不一定相等
 */
public class HashCodeTest {
	public static void main(String[] args) {
		Map<Student,String> map = new HashMap<>();
		map.put(new Student("张三",12), "1");
		map.put(new Student("张三",12), "1");
		for(Entry<Student,String> entry:map.entrySet()) {
			System.out.println(entry.getKey());
		}
	}
	static class Student{
		private String name;
		private Integer age;
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public Integer getAge() {
			return age;
		}
		public void setAge(Integer age) {
			this.age = age;
		}
		public Student(String name, Integer age) {
			super();
			this.name = name;
			this.age = age;
		}
		@Override
		public int hashCode() {
			int hashCode = 0;
			if (name != null) {
				hashCode += name.hashCode();
			}
			if (age != null) {
				hashCode += age.hashCode();
			}
			return hashCode;
		}
		@Override
		public boolean equals(Object obj) {
			if (this == obj) {
				return true;
			}
			if (obj instanceof Student) {
				Student test = (Student) obj;
				if (!this.getName().equals(test.getName())) {
					return false;
				}
				if (!this.getAge().equals(test.getAge())) {
					return false;
				}
				return true;
			}
			return false;
		}
		@Override
		public String toString() {
			return "Student [name=" + name + ", age=" + age + "]";
		}
	}
}
